package byx.container.annotation.demo.StrategyDemo.b;

import byx.container.annotation.annotation.AnnotatedBy;
import byx.container.annotation.annotation.Register;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@Register
public class StrategyRunner {
    private final Map<String, Function<String, String>> strategyMap = new HashMap<>();

    public StrategyRunner(@AnnotatedBy(Strategy.class) List<?> strategies) {
        for (Object s : strategies) {
            String id = s.getClass().getAnnotation(Strategy.class).value();
            for (Method m : s.getClass().getMethods()) {
                if (m.isAnnotationPresent(StrategyMethod.class)) {
                    strategyMap.put(id, input -> {
                        try {
                            return (String) m.invoke(s, input);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    });
                    break;
                }
            }
        }
    }

    public String run(String id, String input) {
        return strategyMap.get(id).apply(input);
    }
}
